<template>
    <div class="page">
        <gzg-search :config="searchConfig" :showMore="true" :form="searchForm" :label-width="120"
            @search="search"></gzg-search>

        <div class="tool-wrap">
            <el-button class="btn" type="primary" @click="add">新增</el-button>
        </div>
        <div class="grid-wrap">
            <el-table style="width:100%;" height="100%" row-key="id" :data="tableData">
                <el-table-column label="手机号码" prop="mobile"></el-table-column>
                <el-table-column label="姓名" prop="real_name"></el-table-column>
                <el-table-column label="状态">
                    <template #default="props">
                        <div>{{ props.row.status == 1 ? '开启' : '关闭' }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="部门" prop="department_name"></el-table-column>
                <el-table-column label="数据权限" prop="data_permission_type_desc"></el-table-column>

                <el-table-column label="角色权限" prop="role_name"></el-table-column>
                <el-table-column label="操作" fixed="right" width="120px">
                    <template #default="props">
                        <el-button link type="primary" size="small" v-if="props.row.button.edit_btn" @click="edit(props.row)">编辑</el-button>
                        <el-button link type="primary" size="small" v-if="props.row.button.close_btn" @click="handleEnable(props.row)">禁用</el-button>
                        <el-button link type="primary" size="small" v-if="props.row.button.open_btn" @click="handleEnable(props.row)">启用</el-button>
                    </template>
                </el-table-column>

            </el-table>
        </div>
        <div class="page-wrap">
            <el-pagination v-model:current-page="params.page"
                           v-model:page-size="params.page_size"
                           :page-sizes="[100, 200, 300, 400]" 
                           layout="total, prev, pager, next" 
                           :total="total"
                           @size-change="handleSizeChange" 
                           @current-change="handleCurrentChange" />

        </div>
        <view-dialog :dialogVisible="dialogVisible" :id="detail_id" :state="dialogState" @success="dialogSuccess"
            @close="dialogVisible = false"></view-dialog>
        <el-dialog v-model="dialogResetVisible" width="480px" title="重置密码">
            <el-form ref="resetFormRef" :model="resetForm" :rules="resetFormRules" :label-width="120">
                <el-form-item prop="password" label="新密码:">
                    <el-input v-model="resetForm.password" :type="passwordShow ? 'text' : 'password'"
                        placeholder="请设置登录密码">
                        <template #suffix>
                            <el-icon @click.stop="passwordShow = !passwordShow" style="cursor: pointer;">
                                <Hide v-if="!passwordShow" />
                                <View v-else />
                            </el-icon>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="password_confirm" label="确认密码">
                    <el-input v-model="resetForm.password_confirm" :type="rePasswordShow ? 'text' : 'password'"
                        placeholder="请确认登录密码">
                        <template #suffix>
                            <el-icon @click.stop="rePasswordShow = !rePasswordShow" style="cursor: pointer;">
                                <Hide v-if="!rePasswordShow" />
                                <View v-else />
                            </el-icon>
                        </template>
                    </el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="cancelReset">取 消</el-button>
                    <el-button type="primary" @click="submitReset(resetFormRef)">确 定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { ref, reactive, watch, computed, onMounted } from 'vue'
import { InfoFilled, Plus, Search, Hide, View } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

import { assign } from 'lodash'

import viewDialog from './component/view-dialog/index'

import systemStore from '@/store/modules/system'

import { getUserList, toggleUser, deleteAccount, resetAccountPassword } from 'services/setting'
import { getRoleList } from 'services/system'


import type { User } from './index'

const $systemStore = systemStore()

const searchForm = reactive({
    role_id: '',
    name: '',
    mobile: '',
    status: '',
})

const searchConfig = reactive([{
    id: 'role_id',
    label: '角色权限',
    placeholder: '请选择角色权限',
    type: 'select',
    text:'role_name',
    key:'id',
    list: []
}, {
    id: 'real_name',
    label: '姓名',
    placeholder: '请输入姓名',
    type: 'input'
}, {
    id: 'mobile',
    label: '手机号',
    placeholder: '请输入手机号',
    type: 'input'
}, {
    id: 'status',
    label: '状态',
    placeholder: '请选择状态',
    type: 'select',
    text:'text',
    key:'value',
    list: [{
        text:'开启',
        value: '1'
    },{
        text:'关闭',
        value: '2'
    }]
}])

const dialogState = ref('edit')

const dialogVisible = ref(false)

const dialogResetVisible = ref(false)

const resetFormRef = ref<FormInstance>()

const passwordShow = ref(false)
const rePasswordShow = ref(false)

const resetForm = reactive({
    id: 0,
    password: '',
    password_confirm: ''
})

const checkPassword = (rule: any, value: any, callback: any) => {
    var reg = /(?!^[0-9]+$)(?!^[a-z]+$)(?!^[A-Z]+$)(?!^[^A-z0-9]+$)^[^\s\u4e00-\u9fa5]/

    if (value === '') {
        callback(new Error('请输入登录密码'))
    } else if (value.length < 6) {
        callback(new Error('密码最少6位'))
    } else if (value.length > 16) {
        callback(new Error('密码最多16位'))

    } else if (!reg.test(value)) {
        callback(new Error('密码需同时包含数字/字母/特殊符号，两种及以上组合'))

    } else {
        callback()
    }
}

const checkRePassword = (rule: any, value: any, callback: any) => {
    if (value != resetForm.password) {
        callback(new Error('与登录密码不一致'))

    } else {
        callback()
    }
}

const resetFormRules = reactive<FormRules>({
    password: [{ validator: checkPassword, required: true, trigger: 'blur' }],
    password_confirm: [{ required: true, validator: checkRePassword, trigger: 'blur' }]
})

const params = ref({
    type: '',
    name: '',
    mobile: '',
    status: '',
    page: 1,
    page_size: 20
})

const search = (searchParams: any) => {

    assign(params.value, searchParams)

    params.value.page = 1

    getList()
}

const detail_id = ref()

const add = () => {
    dialogState.value = 'add'
    detail_id.value = undefined
    dialogVisible.value = true;
}

const edit = (row: User) => {
    dialogState.value = 'edit'
    dialogVisible.value = true
    detail_id.value = row.id
}

const tableData = ref<User[]>([])
const total = ref(0)

const getList = () => {
    getUserList(params.value).then((res: any) => {
        tableData.value = res.items || [];
        total.value = parseInt(res.total_rows) || 0
    })
}

const handleSizeChange = (val: number) => {
    params.value.page_size = val
    params.value.page = 1
    getList();
}

const handleCurrentChange = (val: number) => {
    params.value.page = val
    getList()
}

const handleCommand = (command: string, scope: any) => {
    console.log(command, scope)
    switch (command) {
        case 'enabled':
            handleEnable(scope.row)
            break;
        case 'delete':
            handleDelete(scope.row)
            break;
        case 'reset':
            handleReset(scope.row)
            break;
        default:
            break;
    }
}

const handleReset = (row: User) => {
    resetForm.id = row.id || 0
    dialogResetVisible.value = true
}

const cancelReset = () => {
    dialogVisible.value = false
}

const submitReset = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            resetAccountPassword(resetForm).then((res: any) => {
                dialogVisible.value = false

                ElMessage.success('操作成功')
            })
        } else {
            console.log('error submit', fields)
        }
    })
}

const handleDelete = (row: User) => {
    ElMessageBox.confirm(`账号删除后不可恢复，确定删除“${row.account}”?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then((result) => {
        deleteAccount({ id: row.id || undefined }).then(res => {
            getList()
            ElMessage.success('删除成功')
        })
    }).catch(() => {
        ElMessage.info('已取消删除')
    })
}

const handleEnable = (row: any) => {
    let enabled = row.status;
    ElMessageBox.confirm(`确认进行【${enabled == 1 ? '启用' : '禁用'}】操作`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        toggleUser({
            id: row.id || undefined,
            type: enabled == 1 ? 2 : 1
        }).then(res => {
            getList()
            ElMessage.success('操作成功')
        })
    }).catch(() => {
        ElMessage.info('已取消操作')
    })
}

const dialogSuccess = () => {
    getList();
    dialogVisible.value = false
}

const dict = computed<any>(() => {
    return $systemStore.dict
})

const getInfo = () => {
    getRoleList().then(res => {
        searchConfig[0].list = res.items
    })
}

onMounted(() => {
    getInfo()
    getList()
})
</script>
<style lang="scss">
.tips {
    height: 40px;
    width: 100%;
    display: flex;
    align-items: center;
    font-size: 14px;
    font-family: PingFang SC-Regular, PingFang SC;
    font-weight: 400;
    line-height: 22px;
    margin-bottom: 24px;

    .text {

        color: #606266;
        margin-left: 9px;
    }

    .link {
        color: #2770EE;
        margin-left: 8px;
        text-decoration: none;
    }
}
</style>
